package com.lin.gulimall.product.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lin.gulimall.common.utils.PageUtils;
import com.lin.gulimall.common.utils.Query;
import com.lin.gulimall.common.utils.R;
import com.lin.gulimall.product.config.MyThreadConfig;
import com.lin.gulimall.product.dao.SkuInfoDao;
import com.lin.gulimall.product.entity.SkuImagesEntity;
import com.lin.gulimall.product.entity.SkuInfoEntity;
import com.lin.gulimall.product.entity.SpuInfoDescEntity;
import com.lin.gulimall.product.feign.SeckillFeignService;
import com.lin.gulimall.product.service.*;
import com.lin.gulimall.product.vo.SeckillSkuVo;
import com.lin.gulimall.product.vo.SkuItemSaleAttrVo;
import com.lin.gulimall.product.vo.SkuItemVo;
import com.lin.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author yaoxinjia
 */
@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {


    @Autowired
    private SkuImagesService imagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private SeckillFeignService seckillFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            // String类型数字的比较方法
            BigDecimal bigDecimal = new BigDecimal(max);
            if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                wrapper.le("price", max);
            }
        }
        IPage<SkuInfoEntity> iPage = this.page(new Query<SkuInfoEntity>().getPage(params),wrapper);
        return new PageUtils(iPage);

    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        return this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1、sku基本信息获取 pms_sku_info  多线程异步获取
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        },executor);

        //3、获取spu的销售属性组合 消费处理结果 无返回结果
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        },executor);

        //4、获取spu的介绍 pms_spu_info_desc
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        },executor);

        //5、获取spu的规格参数信息'
        CompletableFuture<Void> attrGroupFuture = infoFuture.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroupVo> attrGroupVos =
                    attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(),res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        },executor);

        //2、sku的图片信息    pms_sku_images  异步执行 不需要返回值
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imagesEntities);
        },executor);

        CompletableFuture<Void> seckillSkuFuture = CompletableFuture.runAsync(() -> {
            // 3.查询当前商品是否参与秒杀优惠
            R r = seckillFeignService.getSkuSeckilInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuVo seckillSkuVo = r.getData(new TypeReference<SeckillSkuVo>(){});
                skuItemVo.setSeckillSkuVo(seckillSkuVo);
            }
        });

        //等到所有任务都完成
        CompletableFuture.allOf(saleAttrFuture,descFuture,attrGroupFuture,imageFuture,seckillSkuFuture).get();
        return skuItemVo;

    }

    @Override
    public BigDecimal getPriceBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = this.baseMapper.selectById(skuId);
        BigDecimal price = skuInfoEntity.getPrice();
        return price;
    }

    @Override
    public List<SkuInfoEntity> getByIds(List<Long> skuIds) {
        return list(new QueryWrapper<SkuInfoEntity>().in("sku_id", skuIds));
    }
}